package net.sourceforge.web.easyui;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;

/**
 * 处理分页，排序，过滤等
 * 
 * @author Alex
 *
 */
public class PivotUtil {
	private final static Gson gson = new Gson();

	private PivotUtil() {
	}

	public static <T> PivotPage<T> parse(final HttpServletRequest req) {
		int rowsPerPage = 10;// default
		try {
			rowsPerPage = Integer.parseInt(req.getParameter("rows"));//
		} catch (NumberFormatException e) {
			// does not provide, use default page size
		}

		int currentPage = 1;
		try {
			currentPage = Integer.parseInt(req.getParameter("page"));//
		} catch (NumberFormatException e) {
			// does not provide, from page 1
		}
		PivotPage<T> pivot = new PivotPage<T>(currentPage, rowsPerPage);

		// 支持多个参数sort=?&sort=?
		String[] sortArray = req.getParameterValues("sort");// columns
		if (sortArray == null)
			sortArray = req.getParameterValues("sortIndex");// 向下兼容
		String[] orderArray = req.getParameterValues("order");
		if (orderArray == null)
			orderArray = req.getParameterValues("sortOrder");// 向下兼容

		if (sortArray != null && sortArray.length > 0) {
			// 每个sort参数可以使用逗号分割
			for (int i = 0; i < sortArray.length; i++) {
				String[] sorts = sortArray[i].split(",");
				String[] orders = orderArray[i].split(",");
				for (int j = 0; j < sorts.length; j++) {
					if ("".equalsIgnoreCase(orders[j]) || "NULL".equalsIgnoreCase(orders[j]))
						continue;
					pivot.addSortParam(sorts[j], orders[j]);
				}
			}
		}
		String fr = req.getParameter("filterRules");
		if (fr != null && fr.length() > 0) {
			JsonParser parser = new JsonParser();
			JsonArray array = parser.parse(fr).getAsJsonArray();
			for (int i = 0; i < array.size(); i++) {
				pivot.getFilterRule().add(gson.fromJson(array.get(i), FilterRule.class));
			}
		}

		req.setAttribute("page", pivot);
		return pivot;
	}
}
